﻿using System;
using System.Globalization;
using System.Windows.Data;

namespace TCC.ControleFluxoDeCaixa.Apresentacao.ResourcesDictionaries.Converters
{
    public class NullableValueConverter : IValueConverter
    {

        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (targetType == null)
                throw new ArgumentNullException("targetType");

            var t = targetType.IsGenericType && targetType.GetGenericTypeDefinition() == typeof (Nullable<>)
                ? targetType.GetGenericArguments()[0]
                : targetType;

            if (t == typeof(DateTime) && targetType.GetGenericTypeDefinition() == typeof(Nullable<>))
            {
                if (string.IsNullOrWhiteSpace((value ?? "").ToString().Replace("/", "").Replace("_", ""))) return null;            
            }

            try
            {
                return System.Convert.ChangeType(value, t, System.Threading.Thread.CurrentThread.CurrentCulture);
            }
            catch (Exception ex)
            {

                return ex;
            }

        }

        #endregion
    }
}